package com.lebo.portal.util;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private final static String[] STRDIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f" };

    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return STRDIGITS[iD1] + STRDIGITS[iD2];
    }

    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String getMd5Value(String str) throws NoSuchAlgorithmException {
        String resultString = null;
        resultString = new String(str);
        MessageDigest md = MessageDigest.getInstance("MD5");
        resultString = byteToString(md.digest(str.getBytes()));
        return resultString;
    }

    public static String md5Pwd(String userName, String password) throws NoSuchAlgorithmException {
        return EncryptUtil.encryptPassword(StringUtils.lowerCase(StringUtils.trim(userName)), password);
    }
}